/**
 * 开单人额度设置 列表页
 *
 * 作者 zhangwei
 * 日期 2024-08-30 09:28:03
 */
layui.use(['jquery', 'laydate', 'febs', 'form', 'table', 'commonJS', 'validate'], function () {
    var $ = layui.jquery,
        laydate = layui.laydate,
        febs = layui.febs,
        form = layui.form,
        table = layui.table,
        commonJS = layui.commonJS,
        validate = layui.validate,
        $view = $('#febs-incentiveQuotaConfig'),
        $query = $view.find('#query'),
        $searchForm = $view.find('#incentiveQuotaConfig-table-form'),
        $tenantSelect = $searchForm.find('select[name="tenantSelect"]'),
        tableIns;

    laydate.render({
        elem: "#year",
        type: "year",
        trigger:'click',
        showBottom:false
    })

    form.verify(validate);
    form.render();

    initTable();

    function initTable() {
        tableIns = febs.table.init({
            elem: $view.find('table'),
            id: 'incentiveQuotaConfigTable',
            url: ctx + 'incentiveQuotaConfig/list',
            where: getQueryParams(),
            height: 'full-130',
            skin: '',
            cols: [[
                {title: '序号',align:'center', type: 'numbers',width: 80},
                {
                    field: 'tenantId',
                    title: '公司名称',
                    width: 160,
                    hide: !hasHeadCompanyRole,
                    templet: function (d) {
                        var tenant = tenantList.filter(item => item.tenantId == d.tenantId);
                        return tenant[0].tenantName;
                    }
                },
                {field: 'year', align:'center',title: '年份', width: 100},{
                    field: 'realName',
                    title: '开单人员',
                    minWidth: 300,
                    // align: 'center',
                    templet: function (d) {
                        var html = '<em class="layui-icon febs-edit-area febs-blue">&#xe7cf;</em>'
                        if (d.realName) {
                            html+=d.realName
                        }
                        html += '&nbsp;<em class="layui-icon febs-edit-area febs-blue">&#xe835;</em>'
                        if (d.userNo) {
                            html+=d.userNo
                        }
                        html += '&nbsp;<em class="layui-icon febs-edit-area febs-blue">&#xe836;</em>'
                        if (d.deptName) {
                            html+=d.deptName
                        }
                        return html
                    }
                },
                {field: 'penaltyBonusRatio',align:'right', title: '罚款奖金比例(%)', width: 180},
                {field: 'totalQuota',align:'right', title: '总额度(元)', width: 160},
                {field: 'rewardedQuota',align:'right', title: '已奖励额度(元)', width: 180},
                {field: 'status',align:'center', title: '状态', width: 100,toolbar: '#status-bar'},
                {title: '操作',align:'center',  toolbar: '#incentiveQuotaConfig-tool', width: 160}
            ]],
            toolbar: '#incentiveQuotaConfig-toolbar',
            defaultToolbar: []
        });
    }

    table.on('sort(incentiveQuotaConfigTable)', function (obj) {
        tableIns.reload({
            initSort: obj,
            where: $.extend(getQueryParams(), {
                field: obj.field,
                order: obj.type
            }),
            autoSort: true
        });
    });

    function reloadPage(curr) {
        var _curr = $view.find(".layui-laypage-em").next().html();
        if (!!curr) {
            _curr = curr;
        }
        tableIns.reload({where: getQueryParams(), page: {curr: _curr}});
    }

    $query.on('click', function () {
        reloadPage(1);
    });

    console.log($tenantSelect.val());

    table.on('toolbar(incentiveQuotaConfigTable)', function (obj) {
        if (obj.event === 'add') {
            febs.modal.open('新增', 'incentiveQuotaConfig/add', {
                btn: ['提交', '取消'],
                area: $(window).width() <= 750 ? '90%': ['800px','600px'],
                yes: function (index, layero) {
                    $('#incentiveQuotaConfig-edit').find('#submit').trigger('click');
                },
                btn2: function () {
                    layer.closeAll();
                },
                data: {
                    tenantId: $tenantSelect.val(),
                }
            });
        } else if (obj.event === 'apply') {
            febs.modal.open('限额申请', 'incentiveQuotaConfig/apply/'+userId, {
                btn: ['提交', '取消'],
                area: $(window).width() <= 750 ? '90%': ['40%','40%'],
                yes: function (index, layero) {
                    $('#incentiveQuotaApply-edit').find('#submit').trigger('click');
                },
                btn2: function () {
                    layer.closeAll();
                },
                data: {
                    tenantId: $tenantSelect.val(),
                }
            });
        }
    });

    table.on('tool(incentiveQuotaConfigTable)', function (obj) {
        var data = obj.data,
        layEvent = obj.event;
        if (layEvent === 'del') {
            febs.modal.confirm('删除数据', '确定删除所选数据？', function () {
                deleteIds(data.quotaConfigId);
            });
        }
        if (layEvent === 'edit') {
            febs.modal.open('修改', 'incentiveQuotaConfig/update/' + data.quotaConfigId, {
                area: $(window).width() <= 750 ? '90%': ['800px','600px'],
                btn: ['提交', '取消'],
                yes: function (index, layero) {
                    $('#incentiveQuotaConfig-edit').find('#submit').trigger('click');
                },
                btn2: function () {
                    layer.closeAll();
                },
                data: {
                    tenantId: $tenantSelect.val(),
                },
            });
        }
    });

    function getQueryParams() {
        return {
            tenantId: $searchForm.find("select[name='tenantSelect']").find("option:selected").val(),
            year: $searchForm.find('input[name="year"]').val()?.trim(),
            realName: $searchForm.find('input[name="realName"]').val()?.trim(),
            userNo: $searchForm.find('input[name="userNo"]').val()?.trim(),
            deptName: $searchForm.find('input[name="deptName"]').val()?.trim(),
            invalidate_ie_cache: new Date()
        };
    }

    function deleteIds(ids) {
        febs.get(ctx + 'incentiveQuotaConfig/delete/' + ids, null, function () {
            febs.alert.success('删除数据成功');
            $query.trigger('click');
        })
    }

    function getTableHeight() {
        return commonJS.calcTableHeight();
    }

    $(window).resize(function () {
        tableIns.reload({height: getTableHeight()});
    });

    form.on('switch(configStatus)', function (obj) {
        //区域状态控制点击事件
        var checked = obj.elem.checked;
        var status;
        if (checked) {
            status = "1";
        } else {
            status = "0";
        }
        //获取该控件所在行
        var index = obj.othis.parents('tr').eq(0).data('index');
        //获取表中所有数据 按行取数据及其 postId
        var id =  table.cache['incentiveQuotaConfigTable'][index].quotaConfigId;
        var year =  table.cache['incentiveQuotaConfigTable'][index].year;
        var userId =  table.cache['incentiveQuotaConfigTable'][index].userId;
        febs.modal.confirm('更改状态', '确认更改状态',function (){
            updateStatus(id,year,userId,status);
        },function (){
            obj.elem.checked = !checked;
            layer.closeAll();
            form.render('checkbox');
        });

    });
    function updateStatus(id,year,userId,status) {
        //更新启用状态
        let model={
            quotaConfigId : id,
            year:year,
            userId,userId,
            status : status
        }
        febs.post(ctx + 'incentiveQuotaConfig/updateStatus', model, function () {
            febs.alert.success('修改状态成功');
            reloadPage(1);
        })
    }

});